package cn.wss.flowable.service.impl;

import cn.wss.flowable.model.FlowableProcessInstance;
import cn.wss.flowable.service.Conditions;
import cn.wss.flowable.service.FlowableRuntimeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class FlowableRuntimeServiceImpl implements FlowableRuntimeService, Conditions {

    @Autowired
    private RuntimeService runtimeService;

    /**
     * @Description 流程启动
     * @Param startUser 启动人
     * @Param variables 参数
     * @Return 部署信息
     */
    @Override
    public FlowableProcessInstance start(Map<String, Object> variables) {
        return startByUser(null, variables);
    }

    /**
     * @Description 流程启动
     * @Param startUser 启动人
     * @Param variables 参数
     * @Return 部署信息
     */
    @Override
    public FlowableProcessInstance startByUser(String startUser, Map<String, Object> variables) {
        // 是否存在key
        if (!variables.containsKey(KEY)) {
            throw new RuntimeException("key不能为空");
        }
        String processKey = (String) variables.get(KEY);
        variables.remove(KEY);

        // 是否存在businessKey
        String businessKey = null;
        if (variables.containsKey(BUSINESS_KEY)) {
            businessKey = (String) variables.get(BUSINESS_KEY);
            variables.remove(BUSINESS_KEY);
        }
        // 设置流程启动人
        if(Strings.isNotBlank(startUser)){
            Authentication.setAuthenticatedUserId(startUser);
        }
        // 启动流程
        ProcessInstance processInstance = null;
        if (StringUtils.isNotBlank(businessKey)) {
            processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey, variables);
        } else {
            processInstance = runtimeService.startProcessInstanceByKey(processKey, variables);
        }
        // 清空流程启动人
        if(Strings.isNotBlank(startUser)) {
            Authentication.setAuthenticatedUserId(null);
        }
        FlowableProcessInstance instance = new FlowableProcessInstance();
        BeanUtils.copyProperties(processInstance, instance);
        return instance;
    }

    /**
     * @Description 流程结束
     * @Param id 流程实例id
     * @Param reason 原因
     * @Return 部署信息
     */
    @Override
    public void finish(String processInstanceId, String reason) {
        runtimeService.deleteProcessInstance(processInstanceId, reason);
    }
}
